<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/13
 * Time: 17:18
 */

namespace App\Services;
use App\Models\CartItem;
use Auth;

class CartService
{
    /**
     * 获得购物车商品列表
     * @return mixed
     */
    public function get()
    {
        return Auth::user()->CartItems()->with(['productSku.product'])->get();
    }

    /**
     * 加入购物车
     * @param $skuId
     * @param $amount
     * @return CartItem
     */
    public function add($skuId, $amount)
    {
        $user = Auth::user();

        //购物车是否存在
        if ($item = $user->cartItems()->where('product_sku_id',$skuId)->first()){
            //存在叠加数量
            $item->update([
                'amount' => $item->amount + $amount,
            ]);
        }else{
            //创建新记录
            $item = new CartItem(['amount' => $amount]);
            $item->user()->associate($user);
            $item->productSku()->associate($skuId);
            $item->save();
        }
        return $item;
    }

    public function remove($skuIds)
    {
        if (!is_array($skuIds)){
            $skuIds = [$skuIds];
        }
        Auth::user()->cartItems()->whereIn('product_sku_id', $skuIds)->delete();
    }
}